using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using Google.GData.Client;
using Google.GData.Contacts;
using Google.GData.Extensions;

namespace Hansvits.MyGoogle.Contacts
{
    public partial class ContactWindow : Form
    {
        ContactEntry _current;
        bool _loading, _removing;

        public ContactWindow()
        {
            InitializeComponent();
            this.BackColor = ColorTranslator.FromHtml("#d4e4ff");
            this.lvItems.BackColor = ColorTranslator.FromHtml("#d4e4ff");

            this.dgvAddresses.BackgroundColor = ColorTranslator.FromHtml("#d4e4ff");
            this.dgvAddresses.RowHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#8EC3FF");
            this.dgvAddresses.ColumnHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#8EC3FF");
            this.dgvAddresses.RowsDefaultCellStyle.SelectionBackColor = ColorTranslator.FromHtml("#ffffcc");
            this.dgvAddresses.RowsDefaultCellStyle.SelectionForeColor = SystemColors.ControlText;

            this.dgvPhones.BackgroundColor = ColorTranslator.FromHtml("#d4e4ff");
            this.dgvPhones.RowHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#8EC3FF");
            this.dgvPhones.ColumnHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#8EC3FF");
            this.dgvPhones.RowsDefaultCellStyle.SelectionBackColor = ColorTranslator.FromHtml("#ffffcc");
            this.dgvPhones.RowsDefaultCellStyle.SelectionForeColor = SystemColors.ControlText;
            
            this.dgvEmails.BackgroundColor = ColorTranslator.FromHtml("#d4e4ff");
            this.dgvEmails.RowHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#8EC3FF");
            this.dgvEmails.ColumnHeadersDefaultCellStyle.BackColor = ColorTranslator.FromHtml("#8EC3FF");
            this.dgvEmails.RowsDefaultCellStyle.SelectionBackColor = ColorTranslator.FromHtml("#ffffcc");
            this.dgvEmails.RowsDefaultCellStyle.SelectionForeColor = SystemColors.ControlText;

            this.lblStatus.Text = "";
            _removing = false;
            _loading = false;
        }

        private void ContactWindow_Load(object sender, EventArgs e)
        {
            _loading = true;
            ListContacts();
            _loading = false;
        }

        private void lvItems_ItemChecked(object sender, ItemCheckedEventArgs e)
        {
            if (_loading == false)
            {
                if (lvItems.CheckedItems.Count > 1)
                {
                    lblStatus.Text = string.Format("{0} items selected", lvItems.CheckedItems.Count);
                }
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            SaveEntry();
            lblStatus.Text = "current entry has been posted";
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            _removing = true;
            int i = 0;
            foreach (ListViewItem item in lvItems.CheckedItems)
            {
                AtomId id = new AtomId(item.Name);
                ContactEntry entry = (ContactEntry) ContactManager.Entries.FindById(id);
                if (entry != null)
                {
                    entry.Delete();
                    lvItems.Items.Remove(item);
                    i++;
                }
            }
            lblStatus.Text = string.Format("{0} contacts removed from the list", i);
            _removing = false;
            lvItems.Items[0].Selected = true;
            ListViewItem selected = lvItems.FindNearestItem(SearchDirectionHint.Up, 0, 0);
            if (selected != null)
            {
                selected.Selected = true;
            }
            else
            {
                if (lvItems.Items.Count > 0)
                {
                    lvItems.Items[0].Selected = true;
                }
            }
        }

        private void ListContacts()
        {
            foreach (ContactEntry entry in ContactManager.Entries)
            {
                ListContact(entry);
            }

            lblStatus.Text = "loaded all contacts in the list";
            lblCount.Text = string.Format("{0} entries", ContactManager.Entries.Count);
        }

        private void ListContact(ContactEntry entry)
        {
            ListViewItem item = new ListViewItem();
            item.Name = entry.Id.AbsoluteUri;
            item.Text = entry.Title.Text;
            item.BackColor = ColorTranslator.FromHtml("#fff");
            lvItems.Items.Add(item);
        }

        private void DisplayEntry(string id)
        {
            AtomId aid = new AtomId(id);
            _current = (ContactEntry) ContactManager.Entries.FindById(aid);
            if (_current != null)
            {

                txtFullname.Text = _current.Title.Text;
                lblUpdated.Text = string.Format("Last Updated\n\t{0}",  _current.Updated);

                txtCompany.Text = "";
                txtJobTitle.Text = "";
                if (_current.Organizations.Count > 0)
                {
                    txtCompany.Text = _current.Organizations[0].Name;
                    txtJobTitle.Text = _current.Organizations[0].Title;
                }

                dgvEmails.Rows.Clear();
                foreach (EMail item in _current.Emails)
                {
                    object[] row = { item.Primary, item.Address, ContactManager.GetLookup(item.Rel) };
                    dgvEmails.Rows.Add(row);
                }

                dgvPhones.Rows.Clear();
                foreach (PhoneNumber item in _current.Phonenumbers)
                {
                    object[] row = { item.Primary, item.Value, ContactManager.GetLookup(item.Rel) };
                    dgvPhones.Rows.Add(row);
                }

                dgvAddresses.Rows.Clear();
                foreach (PostalAddress item in _current.PostalAddresses)
                {
                    object[] row = { item.Primary, item.Value, ContactManager.GetLookup(item.Rel) };
                    dgvAddresses.Rows.Add(row);
                }

                txtNotes.Text = _current.Content.Content;
            }
            else
            {
                txtFullname.Text = "";
                txtCompany.Text = "";
                txtJobTitle.Text = "";
                txtNotes.Text = "";
                dgvEmails.Rows.Clear();
                dgvPhones.Rows.Clear();
                dgvAddresses.Rows.Clear();
                lblUpdated.Text = string.Format("Created\n\t{0}", DateTime.Now.ToString());
            }
        }

        private void SaveEntry()
        {
            bool primary;
            string type, data;
            int index = -1;
            index = ContactManager.Entries.IndexOf(_current);
            if (index < 1)
            {
                _current = new ContactEntry();
            }
            _current.Title.Text = txtFullname.Text;

            _current.Organizations.Clear();
            if (txtCompany.Text.Length > 0)
            {
                Organization o = new Organization();
                o.Name = txtCompany.Text;
                o.Title = txtJobTitle.Text;
                o.Rel = ContactManager.GetRelationship("work");
                o.Primary = true;
                _current.Organizations.Add(o);
            }

            _current.Emails.Clear();
            foreach (DataGridViewRow row in dgvEmails.Rows)
            {
                if (row.IsNewRow == false)
                {
                    primary = (bool)row.Cells["dgvEmailPrimary"].FormattedValue;
                    data = (string)row.Cells["dgvEmailAddress"].FormattedValue;
                    type = (string)row.Cells["dgvEmailType"].FormattedValue;
                    EMail item = new EMail(data);
                    item.Rel = ContactManager.GetRelationship(type);
                    item.Primary = primary;
                    _current.Emails.Add(item);
                }
            }

            _current.Phonenumbers.Clear();
            foreach (DataGridViewRow row in dgvPhones.Rows)
            {
                if (row.IsNewRow == false)
                {
                    primary = (bool)row.Cells["dgvPhonePrimary"].FormattedValue;
                    data = (string)row.Cells["dgvPhoneAddress"].FormattedValue;
                    type = (string)row.Cells["dgvPhoneType"].FormattedValue;
                    PhoneNumber item = new PhoneNumber(data);
                    item.Rel = ContactManager.GetRelationship(type);
                    item.Primary = primary;
                    _current.Phonenumbers.Add(item);
                }
            }

            _current.PostalAddresses.Clear();
            foreach (DataGridViewRow row in dgvAddresses.Rows)
            {
                if (row.IsNewRow == false)
                {
                    primary = (bool)row.Cells["dgvAddressPrimary"].FormattedValue;
                    data = (string)row.Cells["dgvAddressAddress"].FormattedValue;
                    type = (string)row.Cells["dgvAddressType"].FormattedValue;
                    PostalAddress item = new PostalAddress(data);
                    item.Rel = ContactManager.GetRelationship(type);
                    item.Primary = primary;
                    _current.PostalAddresses.Add(item);
                }
            }

            _current.Content.Content = txtNotes.Text;

            _current = ContactManager.Publish(_current);
            SyncDisplay(_current);
        }

        private void ContactWindow_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason != CloseReason.WindowsShutDown)
            {
                if (MessageBox.Show(this, "Do you really want to exit?", "Closing ...", MessageBoxButtons.YesNo) == DialogResult.No)
                {
                    e.Cancel = true;
                }
            }
        }

        private void ContactWindow_FormClosed(object sender, FormClosedEventArgs e)
        {
            Application.Exit();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            DisplayEntry("");
        }

        private void lvItems_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (_loading == false & _removing == false)
            {
                ChangeChecked(e.Item);
                DisplayEntry(e.Item.Name);
                lblStatus.Text = "";
            }
        }

        private void ChangeColor(ListViewItem current)
        {
            if (current.ListView != null)
            {
                foreach (ListViewItem item in current.ListView.Items)
                {
                    item.BackColor = ColorTranslator.FromHtml("#fff");
                }
            }
            current.BackColor = ColorTranslator.FromHtml("#ffffcc");
        }

        private void ChangeChecked(ListViewItem current)
        {
            if (current.ListView != null)
            {
                foreach (ListViewItem item in current.ListView.Items)
                {
                    item.Checked = false;
                }
            }
            current.Checked = true;
        }

        private void lvItems_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {
            if (_loading == false & _removing == false)
            {
                ChangeColor(e.Item);
            }            
        }

        private void SyncDisplay()
        {
            foreach (ContactEntry entry in ContactManager.Entries)
            {
                ListViewItem[] items = lvItems.Items.Find(entry.Id.AbsoluteUri, true);
                if (items == null)
                {
                    ListContact(entry);
                }
                else
                {
                    foreach (ListViewItem item in items)
                    {
                        if (item.Text != entry.Title.Text)
                        {
                            item.Text = entry.Title.Text;
                        }
                    }
                }
            }
        }

        private void SyncDisplay(ContactEntry entry)
        {
            if (entry == null)
                return;
            ListViewItem[] items = lvItems.Items.Find(entry.Id.AbsoluteUri, true);
            if (items == null || items.Length == 0)
            {
                ListContact(entry);
            }
            else
            {
                foreach (ListViewItem item in items)
                {
                    if (item.Text != entry.Title.Text)
                    {
                        item.Text = entry.Title.Text;
                    }
                }
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            ListViewItem item = lvItems.FindItemWithText(txtSearch.Text, false, 0, true);
            if (item != null)
            {
                item.Selected = true;
            }
        }

    }
}